package com.etong.citymap.connect;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.etong.citymap.module.Image;
import com.etong.citymap.util.StringUtil;
import com.etong.citymap.util.log.LogDetailUtil;
import com.etong.citymap.util.log.LogUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpSendData {


	private static int FILESIZE = 2*1024;

	public static String SendPost(String url, Map<String, String> map, String httpUrl) {
//		try {
//			HttpPost request = new HttpPost(httpUrl + url);
//			JSONObject param = new JSONObject(map);
//			StringEntity se = new StringEntity(param.toString());
//			request.setEntity(se);
//			HttpResponse httpResponse = new DefaultHttpClient()
//			.execute(request);
//			String retSrc = EntityUtils.toString(httpResponse.getEntity());
//			return retSrc;
//		} catch (Exception e) {
//			LogUtil.e(e);
//		}
//		return null;
		try {
			return SendGet(url, map, "UTF-8", httpUrl);
		} catch (Exception e) {
			LogUtil.e(e);
		}
		return null;
	}

	public static String SendGet(String path, Map<String, String> parms, String encoding, String httpUrl) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append(httpUrl);
		sb.append(path);
		if (parms != null && !parms.isEmpty()) {
			sb.append("?");
			for (Entry<String, String> entry : parms.entrySet()) {
				sb.append(entry.getKey()).append('=')
				.append((StringUtil.IsNotNull(entry.getValue())?URLEncoder.encode(entry.getValue(), encoding):""))
				.append('&');
			}
			sb.deleteCharAt(sb.length() - 1);
		}
		return HttpGetData(sb.toString());
	}

	public static Bitmap getImage(String Url) throws Exception {
		try {
			URL url = new URL(Url);
			String responseCode = url.openConnection().getHeaderField(0);
			if (responseCode.indexOf("200") < 0)
				throw new Exception("图片文件不存在或路径错误，错误代码：" + responseCode);
			return BitmapFactory.decodeStream(url.openStream());
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		}

	}

	public static synchronized  Bitmap returnBitMap(String url) {
		URL myFileUrl = null;
		Bitmap bitmap = null;
		try {
			myFileUrl = new URL(url);
		} catch (MalformedURLException e) {
			LogUtil.e(e);
		}
		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			LogUtil.e(e);
		}
		return bitmap;
	}

	public static String SendTextAndFile(String actionUrl,
			Map<String, String> params, String imagepath, String httpUrl) throws IOException {
		StringBuilder sba = new StringBuilder();
		for (Entry<String, String> entry : params.entrySet()) {
			sba.append(entry.getKey()).append('=')
			.append(URLEncoder.encode(entry.getValue(), "utf-8"))
			.append('&');
		}
		sba.deleteCharAt(sba.length() - 1);
		URL uri = new URL(httpUrl + actionUrl + "?" + sba.toString());
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setReadTimeout(5 * 1000);
		conn.setDoInput(true);// 允许输入
		conn.setDoOutput(true);// 允许输出
		conn.setUseCaches(false);
		conn.setRequestMethod("POST"); // Post方式
		OutputStream outputStream = conn.getOutputStream();
		byte[] bs = new byte[1024];
		int len = 0;
		File file = new File(imagepath);
		InputStream inputStream = new FileInputStream(file);
		while ((len = inputStream.read(bs)) > 0) {
			outputStream.write(bs, 0, len);
		}
		outputStream.flush();
		outputStream.close();
		inputStream.close();
		int code = conn.getResponseCode();
		if (code == 200) {
			inputStream = conn.getInputStream();
			len = 0;
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			while ((len = inputStream.read(bs)) > 0) {
				stream.write(bs, 0, len);
			}
			inputStream.close();
			return stream.toString();
		}
		return "-1";
	}


	private static String HttpGetData(String url) {
		LogDetailUtil.i("HttpGetData___Url=" + url);
		String rev = null;
		try {
			OkHttpClient client = new OkHttpClient();// 创建OkHttpClient对象
			Request request = new Request.Builder().url(url)// 请求接口。如果需要传参拼接到接口后面。
					.build();// 创建Request 对象
			Response response = null;
			response = client.newCall(request).execute();// 得到Response 对象
			LogDetailUtil.i("HttpGetData_response->" + response);
			if (response.isSuccessful()) {
				LogDetailUtil.d("HttpGetData_response.code()==" + response.code()+ " response.message()==" + response.message());
				int code = response.code();
				if(code==200) {
					rev=response.body().string();
					LogDetailUtil.d("HttpGetData_response.body()->" + rev);
				}
				// 此时的代码执行在子线程，修改UI的操作请使用handler跳转到UI线程。
			}
		} catch (Exception e) {
			LogUtil.e(e);
		}
		return rev;
	}

	public static String SendWorkStat(String path, Map<Object, Object> parms, String encoding, Image[] images, String httpUrl) throws Exception {
		try{
			String response = new UploadImage().post(httpUrl+path, parms, images);
			return response;
		}catch(Exception e){
			LogUtil.e(e);
			return null;
		}
	}


	/**  
	 *   
	 * @param urlStr  
	 * @param path  
	 * @param fileName  
	 * @return   
	 *      -1:文件下载出错  
	 *       0:文件下载成功  
	 *       1:文件已经存在  
	 */  
	public static int downFile(String urlStr, String path, String fileName){  
		InputStream inputStream = null;  
		try {  
			inputStream = getInputStreamFromURL(urlStr);  
			File resultFile = write2SDFromInput(path, fileName, inputStream);  
			if(resultFile == null){  
				return -1;  
			}  
		}   
		catch (Exception e) {  
			LogUtil.e(e);  
			return -1;  
		}  
		finally{  
			try {  
				inputStream.close();  
			} catch (IOException e) {  
				LogUtil.e(e);  
			}  
		}  
		return 0;  
	}

	/**  
	 * 根据URL得到输入流  
	 * @param urlStr  
	 * @return  
	 */  
	public static InputStream getInputStreamFromURL(String urlStr) {  
		HttpURLConnection urlConn = null;  
		InputStream inputStream = null;  
		try {  
			URL url = new URL(urlStr);  
			urlConn = (HttpURLConnection)url.openConnection();  
			inputStream = urlConn.getInputStream();  

		} catch (MalformedURLException e) {  
			LogUtil.e(e);  
		} catch (IOException e) {  
			LogUtil.e(e);  
		}  

		return inputStream;  
	} 

	/**  
	 * 将一个InputStream里面的数据写入到SD卡中  
	 * @param path  
	 * @param fileName  
	 * @param input  
	 * @return  
	 */  
	public static File write2SDFromInput(String path,String fileName,InputStream input){  
		File file = null;  
		OutputStream output = null;  
		try {  
			file = new File(path + fileName);  
			output = new FileOutputStream(file);  
			byte[] buffer = new byte[FILESIZE];  

			/*真机测试，这段可能有问题，请采用下面网友提供的  
                        while((input.read(buffer)) != -1){  
            output.write(buffer);  
        }  
			 */  

			/* 网友提供 begin */  
			int length;  
			while((length=(input.read(buffer))) >0){  
				output.write(buffer,0,length);  
			}  
			/* 网友提供 end */  

			output.flush();  
		}   
		catch (Exception e) {  
			LogUtil.e(e);  
		}  
		finally{  
			try {  
				output.close();  
			} catch (IOException e) {  
				LogUtil.e(e);  
			}  
		}  
		return file;  
	} 
}
